<?php

namespace app\index\controller;

use think\Db;
use think\File;

/* * **********************************************
 * 
 * 支付模块
 * https://www.kancloud.cn/polo1559/pay_super/693141
 * 
 * ***********************************************
 * 
 * 充值--暂定 金币：人民币=1:1 不送
 * 积分：人民币=100:1
 * 
 */

class Pay extends Common {

    protected $table = 'chat_userwallet'; //钱包
    protected $w_table = 'chat_withdrawaccount'; //提现账号表
    protected $s_table = 'chat_withdrawals'; //提现余额账号表
    protected $l_table = 'chat_balancelog'; //余额日志表
    protected $r_table = 'chat_recharge'; //充值表
    protected $p_table = 'chat_point_log'; //积分明细表
    protected $g_table = 'chat_gift'; //礼物表
    protected $glog_table = 'chat_give'; //礼物表明细
    //支付配置
    protected $key = '084f10432cec4065a51547dce31fae60';
    protected $id = '12198';

    // 充值，付费，消费，体现

    /**
     * 生成签名
     */
    private function sign($arr) {

        ksort($arr);
        $str = http_build_query($arr) . '&key=' . $this->key;
        return md5($str);
    }

    //我的账户， 积分账户，金币账户，没有的话创建1个

    public function myAccount() {
        $map = [
            'user_uid' => input('param.user_uid'),
            'app_flag' => input('param.app_flag'),
        ];
        $data = Db::table($this->table)->where($map)->field('balance,point')->find();
        if ($data) {
            return retData($data, '1000', 'ok');
        } else {
            return retData(['balance' => 0, 'point' => 0], '1000', 'ok');
        }
    }

    //充值支付
    public function Pay() {
        $url = 'http://www.fjlmnet.com/api/v3.index/wangshang';
        $post = [
            'mchid' => $this->id,
            'trade_sn' => time() . rand('10000', '99999'), //商户号
            'money' => input('param.money'),
            'payChannel' => input('param.payChannel'), //ALIPAY,WEIXIN
            'redirect' => 0,
            'notifyurl' => '',
        ];

        $sign = $this->sign($post);
        $post['sign'] = $sign;

        $data = curl_request($url, $post);

        if ($data['code'] == 1) {
            $state = 1; //成功
        } else {
            $state = 2; //失败
        }

        //支付成功---插入数据库
        /*         * *
         * 1.根据user_uid、app_flag查询用户信息，
          2.如果不是测试账号，返回“非测试用账号，禁止充值”，
          3.根据app标志获得汇率 ratio，
          4.生成随机的充值订单号，
          5.生成充值清单 （Recharge表），
          6.生成账户余额日志表 （BalanceLog表）  日志记录金额：money * ratio，
          7.获取用户钱包信息，
          8.如果传入的 state = 2，返回“充值失败”
          9.用户钱包修改：balance = 钱包余额 + （money * ratio），moneyrecharge = moneyrecharge + money
          10.设置分享者贡献值：根据 userUid、AppFlag=mt、IsLock=1 来获得充值用户的信息， 查询该用户有无userParentUid，有就查询userParentUid的钱包，给userParentUid的钱包的MoneyShare 加上用户充值的 money
         */

        Db::startTrans();
        try {
            //充值表
            $insert = [
                'user_uid' => input('param.user_uid'),
                'order_no' => $this->orderId('CZ'), //生成订单号方法
                'money' => input('param.money'),
                'type' => input('param.payChannel') == 'ALIPAY' ? 2 : 1, //支付方式
                'app_flag' => input('param.app_flag'),
                'ctime' => time(),
                'state' => $state,
            ];
            Db::table($this->r_table)->insert($insert);
            if ($state == 1) {
                //查询当前账号余额
                $chat_userwallet = Db::table($this->table)->where(['user_uid' => input('param.user_uid')])->find();

                $new_blance = input('param.money') + $chat_userwallet['balance'];
                $log_insert = [
                    'user_uid' => $insert['user_uid'],
                    'order_no' => $insert['order_no'], //生成订单号方法
                    'content' => '0,金币充值,' . input('param.money'), //记录
                    'money' => input('param.money'),
                    'balance' => $new_blance,
                    'type' => 2, //充值
                    'app_flag' => input('param.app_flag'),
                    'ctime' => time(),
                ];
                //插入日志
                Db::table($this->l_table)->insert($log_insert);

                //更新钱包金额
                Db::table($this->table)->where(['user_uid' => input('param.user_uid')])->save(['balance' => $new_blance]);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }

    //视频互动
    // 接通前 --接通中--挂断（余额不足）
    public function livePay() {
        
    }

    //金币记录明细
    //积分记录明细
    //积分转换金币
    //积分提现
    //交易--充值， 礼物赠送，真心话付费，私密视频付费
    //任务赚金币 ，分销赚金币
    // 正常的收支（含签到），还有推广的收支，
    //获取礼物列表
    public function giftList() {
        $data = Db::table($this->g_table)
                ->where(['state' => 1, 'app_flag' => input('param.app_flag')])
                ->select(['id', 'icon', 'name', 'gold']);
        return retData($data, '1000', 'ok');
    }

    //礼物赠送
    /**
     * 思路：用户消费记录，主播加钱记录。礼物赠送记录
     * @return type
     */
    public function giveGift() {
        $user_uid = input('param.user_uid');
        $order_no = $this->orderId('ZS');
        $money = input('param.money');
        $app_flag = input('param.app_flag');
        $user_uid_receive = input('param.user_uid_receive'); //主播
        $gift_name = input('param.gift_name'); //主播
        $gift_gold = input('param.gift_gold'); //主播
        $gift_id = input('param.gift_id'); //主播

        Db::startTrans();
        try {
            //A用户扣钱--记录消费日志，账户余额减
            $user_conent = '2,' . $user_uid_receive . ',' . $gift_name . ',' . $gift_gold;
            $user_log = $this->incomeLog($user_uid, $order_no, $money, '1', $user_conent, $app_flag);
            if (!$user_log) {
                return retData([], '1001', '余额不足');
            }

            //主播加钱
            $user_uid_receive_conent = '1,' . $user_uid . ',' . $gift_name . ',' . $gift_gold;
            $receive_order_no = $this->orderId('SH'); //收获
            $user_uid_receive_log = $this->incomeLog($user_uid_receive, $receive_order_no, $money, '3', $user_uid_receive_conent, $app_flag);
            if ($user_uid_receive_log) {
                $insert = [
                    'user_uid' => $user_uid,
                    'user_uid_receive' => $user_uid_receive, //主播ID
                    'order_no' => $order_no, //生成订单号方法
                    'money' => $money,
                    'gift_id' => $gift_id, //礼物ID
                    'gift_name' => $gift_name, //礼物ID
                    'gift_gold' => $gift_gold, //礼物ID
                    'app_flag' => $app_flag,
                    'ctime' => time(),
                ];
                //赠送记录
                Db::table($this->log_table)->insert($insert);
            }
            return retData([], '1000', '打赏成功');
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return retData([], '1001', '打赏失败');
        }
    }

    /**
     * 账户变动记录
     * @param type $user_uid 用户ID
     * @param type $order_no 订单号
     * @param type $money 金额
     * @param type $type 1消费2充值3收益4提现5其他（管理员修改等）
     * @param type $content 记录内容
     * @param type $app_flag 
     */
    protected function incomeLog($user_uid, $order_no, $money, $type, $content, $app_flag) {

        $chat_userwallet = Db::table($this->table)->where(['user_uid' => $user_uid])->find();
        if ($type == 1 || $type == 4) {
            if ($chat_userwallet['balance'] < $money) {
                return false;
            } else {
                $new_blance = $chat_userwallet['balance'] - $money; //更新后金币
            }
        } else {
            $new_blance = $chat_userwallet['balance'] + $money; //更新后金币
        }

        // 更新账户记录

        $log_insert = [
            'user_uid' => $user_uid,
            'order_no' => $order_no, //生成订单号方法
            'content' => $content, //记录
            'money' => $money,
            'balance' => $new_blance,
            'type' => $type,
            'app_flag' => $app_flag,
            'ctime' => time(),
        ];
        //插入日志
        Db::table($this->l_table)->insert($log_insert);
        //更新钱包金额
        Db::table($this->table)->where(['user_uid' => $user_uid])->save(['balance' => $new_blance]);

        return true;
    }

}
